package com.zzl.example.springboottest.util;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class AmountAccumulator {
 
    public static <T> BigDecimal accumulateAmounts(List<T> items, Class<T> clazz) {
        Field[] fields = clazz.getDeclaredFields();
        List<Field> amountFields = Arrays.stream(fields)
                .filter(field -> field.getType().equals(BigDecimal.class))
                .collect(Collectors.toList());




        return items.stream()
                .map(item -> accumulateItemAmounts(item, amountFields))
                .reduce(BigDecimal.ZERO, BigDecimal::add);
    }
 
    private static <T> BigDecimal accumulateItemAmounts(T item, List<Field> amountFields) {
        return amountFields.stream()
                .map(field -> {
                    field.setAccessible(true);
                    try {
                        return (BigDecimal) field.get(item);
                    } catch (IllegalAccessException e) {
                        throw new RuntimeException(e);
                    }
                })
                .reduce(BigDecimal.ZERO, BigDecimal::add);
    }

    public static void main(String[] args) {
        List<Item> items = Arrays.asList(
                new Item(BigDecimal.TEN, BigDecimal.ONE, "101"),
                new Item(BigDecimal.TEN, BigDecimal.TEN, "1010"),
                new Item(BigDecimal.ONE, BigDecimal.TEN, "110")
        );

        BigDecimal total = accumulateAmounts(items, Item.class);
        // 输出总金额
        System.out.println("Total: " + total);
    }
}